﻿using LSL.SqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Liu_Project.Utils
{
    public static class ExtensionMethods
    {
        public static void SetPropertyValue<T>(this T entity, string propertyName, object value)
        {
            Type t = entity.GetType();
            if (t == null) return;
            PropertyInfo propertyInfo = t.GetProperty(propertyName);
            if (propertyInfo == null) return;
            if (propertyInfo.CanWrite)
                propertyInfo.SetValue(entity, value.ConvertSimpleType(propertyInfo.PropertyType), null);
            // propertyInfo.SetValue(entity, value, null);

        }

        public static object ConvertSimpleType(this object value, Type destinationType)
        {
            object returnValue;
            if ((value == null) || destinationType.IsInstanceOfType(value))
            {
                return value;
            }
            string str = value as string;
            if ((str != null) && (str.Length == 0))
            {
                return null;
            }
            TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
            bool flag = converter.CanConvertFrom(value.GetType());
            if (!flag)
            {
                converter = TypeDescriptor.GetConverter(value.GetType());
            }
            if (destinationType.Name == "Boolean" && (value.ToString() == "1" || value.ToString() == "0"))
            {
                if (DataConvert.ToString(value) == "1")
                    return true;
                else
                    return false;
            }
            else if (destinationType.Name == "Decimal")
            {
                return DataConvert.ToDecimal(value);
            }

            if (!flag && !converter.CanConvertTo(destinationType))
            {
                throw new InvalidOperationException("无法转换成类型：" + value.ToString() + "==>" + destinationType);
            }
            try
            {

                returnValue = flag ? converter.ConvertFrom(null, null, value) : converter.ConvertTo(null, null, value, destinationType);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("类型转换出错：" + value.ToString() + "==>" + destinationType, e);
            }
            return returnValue;
        }

    }
}
